package cn.luckday.config;

import cn.luckday.action.Action;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class ActionConfig {
    private static Map<String, String> configMap = new HashMap();

    static {
        try {
            // 创建一个SAXReader对象
            SAXReader reader = new SAXReader();
            // 读取XML文件，获取Document对象
            Document document = reader.read(new File(AppConfig.getProperty("configPath")));

            // 获取XML文档的根元素
            Element rootElement = document.getRootElement();
            List<Element> elements = rootElement.elements();
            for (Element element : elements) {
                configMap.put(element.attributeValue("name"), element.attributeValue("class"));
            }

        } catch (Exception ex) {
            log.error("Action xml Load err {}", ex.getMessage());
            ex.printStackTrace();
        }
    }

    public static String getClassPath(String key) {
        return configMap.get(key);
    }

    public static Action getAction(String key) {
        try {
            Class<?> clazz = Class.forName(configMap.get(key));
            Constructor<?> constructor = clazz.getDeclaredConstructor();
            constructor.setAccessible(true); //
            return (Action) constructor.newInstance();
        } catch (Exception ex) {
            log.error("Action xml Load err {}", ex.getMessage());
            ex.printStackTrace();
        } finally {
            return null;
        }

    }
}

